/* eslint-disable consistent-return */

import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, Table, Spin, List, Modal, Button, message } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import downloadFile from '@/utils/utils';
import Ellipsis from '@/components/Ellipsis';
import styles from '@/utils/utils.less';
import insImg from '../../../assets/adjust-ins.png';
import accuImg from '../../../assets/adjust-accu.png';
import costCenterImg from '../../../assets/adjust-costcenter.png';
import quoImg from '../../../assets/adjust-quo.png';
import empInfoImg from '../../../assets/adjust-empinfo.png';
import serFeeImg from '../../../assets/adjust-serfee.png';

@connect(({ publicdata, batchadjust, loading }) => ({
  dictCode: publicdata.dictCode,
  data: batchadjust.data,
  loading: loading.effects['batchadjust/fetchList'],
  formFieldsValue: batchadjust.formFieldsValue,
}))
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      batchCount: null, // 提交总数
      batchError: null, // 执行失败
      execStatusName: null, // 执行状态
      allFileId: null, // 文件总数id
      errorFileId: null, // 失败文件id
    };
  }

  componentDidMount = () => {
    const {
      dispatch,
      location,
      data: { pagination },
    } = this.props;
    // 获取字典状态
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['SEND_STATUS'],
    });
    const { isMenuLink } = location.query;
    if (isMenuLink) {
      this.resetAndGeLlist(location);
    } else {
      this.getList(pagination.current, pagination.pageSize);
    }
  };

  // 获取列表
  getList = (currentPage = 1, pageSize = 10) => {
    const { dispatch } = this.props;
    const pageArg = { currentPage, pageSize };
    dispatch({
      type: 'batchadjust/fetchList',
      payload: pageArg,
    });
  };

  // 模态框显隐
  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  // 查看进度
  getProgress = record => {
    this.setState({
      batchCount: record.batchCount,
      batchError: record.batchError,
      execStatusName: record.execStatusName,
      allFileId: record.allFileId,
      errorFileId: record.errorFileId,
    });
    this.handleModalVisible(true);
  };

  // 提交总数下载
  downloadFileSuccess = () => {
    const { allFileId } = this.state;
    if (!allFileId) {
      return message.warning('历史数据无法下载！');
    }
    downloadFile({ fileId: allFileId, fileName: null });
  };

  // 错误条数下载
  downloadFileError = () => {
    const { errorFileId } = this.state;
    if (!errorFileId) {
      return message.warning('历史数据无法下载！');
    }
    downloadFile({ fileId: errorFileId, fileName: null });
  };

  // 下载模板
  downloadInfo = item => {
    const { dispatch } = this.props;
    if (item.id === '4' || item.id === '3') {
      // 如果是成本中心，雇员信息
      dispatch({
        type: 'batchadjust/getDownloadInfo',
        payload: {
          batchAdjType: item.id,
        },
      });
    }
    router.push(`${item.batchPath}?batchAdjType=${item.id}`);
  };

  // 重置查询条件并获取列表
  async resetAndGeLlist(location) {
    await this.getList();
    const { dispatch } = this.props;
    dispatch({
      type: 'batchadjust/updateModelData',
      payload: { expandForm: false },
    });
    dispatch({
      type: 'global/changeIsMenuLink',
      payload: location,
    });
  }

  render() {
    const { data, loading } = this.props;
    const { modalVisible, execStatusName, batchCount, batchError } = this.state;
    // 表格配置：分页器
    const pagination = {
      defaultCurrent: data.pagination.current,
      defaultPageSize: data.pagination.pageSize, // 默认单页条数
      current: data.pagination.current, // 当前页
      pageSize: data.pagination.pageSize, // 单页条数
      total: data && data.pagination.total, // 数据总数
      showQuickJumper: true, // 跳转至某页
      showSizeChanger: true, // 是否可以改变 pageSize
      onChange: (page, pageSize) => {
        // 页码改变的回调
        this.getList(page, pageSize);
      },
      onShowSizeChange: (current, size) => {
        // 单页条数变化的回调
        this.getList(current, size);
      },
      showTotal: total => {
        const totalPage = total < pagination.pageSize ? 1 : Math.ceil(total / pagination.pageSize);
        return `共 ${total} 条记录 第 ${pagination.current} / ${totalPage}页`;
      },
    };
    const columns = [
      {
        title: '操作类型',
        dataIndex: 'batchTypeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val || '--',
      },
      {
        title: '操作时间',
        dataIndex: 'creTime',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => (val ? moment(val).format('YYYY-MM-DD HH:mm') : '--'),
      },
      {
        title: '涉及总人数',
        dataIndex: 'batchCount',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '状态',
        dataIndex: 'execStatusName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '执行错误',
        dataIndex: 'batchError',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => (
          <span>
            <a onClick={() => this.getProgress(record)}>查看</a>
          </span>
        ),
      },
    ];
    const adjustTypeList = [
      {
        id: '1',
        avatar: insImg,
        title: '修改社保申报信息',
        description: '修改缴费方式、缴纳账户、社保组合和申报工资',
        batchPath: '/customservicemanage/adjusttask/batchins',
      },
      {
        id: '2',
        avatar: accuImg,
        title: '修改公积金申报信息',
        description: '修改缴费方式、缴纳账户、公积金组合和申报工资',
        batchPath: '/customservicemanage/adjusttask/batchaccu',
      },
      {
        id: '3',
        avatar: costCenterImg,
        title: '修改所属成本中心',
        description: '修改雇员所属成本中心，当月待收费帐单会自动按照最新成本中心拆分',
        batchPath: '/customservicemanage/adjusttask/batchcostcenter',
      },
      {
        id: '6',
        avatar: quoImg,
        title: '更换所属报价单',
        description: '更换雇员所属报价单',
        batchPath: '/customservicemanage/adjusttask/batchquotation',
      },
      {
        id: '4',
        avatar: empInfoImg,
        title: '修改雇员信息',
        description: '修改内容包括电话、邮箱、入职日期',
        batchPath: '/customservicemanage/adjusttask/batchempinfo',
      },
      {
        id: '5',
        avatar: serFeeImg,
        title: '修改服务费',
        description: '修改当月的服务费',
        batchPath: '/customservicemanage/adjusttask/batchservicefee',
      },
      // {
      //   id: '7',
      //   avatar: areaImg,
      //   title: '修改执行地',
      //   description: '变更雇员的产品执行地',
      //   batchPath: '/customservicemanage/adjusttask/batcharea',
      // },
    ];
    return (
      <PageHeaderWrapper>
        <Spin tip="Loading..." spinning={loading}>
          <Card title="调整项" style={{ marginBottom: 16 }}>
            <List
              rowKey="id"
              grid={{ gutter: 24, xl: 4, xxl: 4, lg: 4, md: 4, sm: 4, xs: 4 }}
              dataSource={adjustTypeList}
              renderItem={item => (
                <List.Item key={item.id}>
                  <Card
                    hoverable
                    className={styles.card}
                    onClick={() => {
                      if (item.id === '7') {
                        message.warning('努力开发中。。。');
                      } else {
                        this.downloadInfo(item);
                      }
                    }}
                    style={{ border: '1px solid #e8e8e8' }}
                  >
                    <Card.Meta
                      avatar={
                        <img alt="调增项目图片" className={styles.cardAvatar} src={item.avatar} />
                      }
                      title={<a style={{ color: '#242424' }}>{item.title}</a>}
                      description={
                        <Ellipsis lines={3} style={{ height: 64 }}>
                          {item.description}
                        </Ellipsis>
                      }
                    />
                  </Card>
                </List.Item>
              )}
            />
          </Card>
          <Card className={styles.tableCard} title="操作记录">
            <Table
              dataSource={data && data.list}
              columns={columns}
              rowKey={record => record.batchId}
              pagination={pagination}
            />
            <Modal
              title={`执行结果(${execStatusName})`}
              closable={false}
              visible={modalVisible}
              footer={[
                <Button key="close" type="primary" onClick={() => this.handleModalVisible(false)}>
                  关闭
                </Button>,
              ]}
            >
              <div style={{ width: '40%', margin: '0 auto' }}>
                <p>
                  <span>提交总数：{batchCount}</span>
                  <a style={{ marginLeft: 20 }} onClick={() => this.downloadFileSuccess()}>
                    下载
                  </a>
                </p>
                <p>
                  <span>执行成功：{batchCount - batchError}</span>
                </p>
                <p>
                  {batchError > 0 ? (
                    <div>
                      <span>执行失败：{batchError}</span>
                      <a style={{ marginLeft: 20 }} onClick={() => this.downloadFileError()}>
                        下载
                      </a>
                    </div>
                  ) : null}
                </p>
              </div>
            </Modal>
          </Card>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}
export default BasicList;
